<?php


/**
 * Resumes controller
 */
class ResumeShare
{
   public static function getToken($itemSource, $itemType, $shareWith=null) {
      $db = PFactory::getDbo();
      /* get pre-generated token */
      $query = "SELECT token FROM *PREFIX*share " .
               " WHERE item_source=" . $db->quote($itemSource) .
               " AND item_type=" . $db->quote($itemType) .
               " AND uid_owner = " . $db->quote(OC_User::getUser()) .
               " AND item_type='resumes' " .
               ($shareWith ? " AND share_with=".$db->quote($shareWith) : " AND share_with IS NULL");

      $db->setQuery(PUtil::replaceOCPrefix($query));
      $token = $db->loadResult();
      return $token;
   }

   public static function setTokenSetting($useToken=0, $itemSource, $itemType, $shareWith='')
   {
      if(empty($itemSource) || empty($itemType))
         return false; 


      $db = PFactory::getDbo();
      $token = 'NULL';
      if($useToken) {
         $token = self::getToken($itemSource, $itemType);
         if(!$token) {
            return false;
         }
      }

      $query = "UPDATE *PREFIX*share SET token=" . $db->quote($token) .
               " WHERE item_source=" . $db->quote($itemSource) .
               " AND item_type=" . $db->quote($itemType) .
               " AND uid_owner = " . $db->quote(OC_User::getUser()) .
               " AND item_type='resumes' " .
               (empty($shareWith) ? "" : " AND share_with=" . $db->quote($shareWith)) . 
               " AND share_with IS NOT NULL";
      $db->setQuery(PUtil::replaceOCPrefix($query));
      $db->execute();

      return true; 
   }

   public static function getSharesByToken($token='', $sharewith='') {
      if(empty($token) || empty($sharewith)) {
         return null; 
      }

      $db = PFactory::getDbo();
      /* get pre-generated token */
      $query = "SELECT * FROM *PREFIX*share WHERE item_type='resumes' AND token=" . $db->quote($token) . ' AND (share_with IS NULL OR share_with=' . $db->quote($sharewith) . ')'; 
      
      $db->setQuery(PUtil::replaceOCPrefix($query));
      $shares = $db->loadObjectList();
      if(!$shares) return null; 

      /* get two share entries, good to return */
      if(count($shares) > 1) return $shares; 

      /* we only get one share which share_with should be null, need to check if user in group */
      if($shares[0]->share_with) return $shares; 

      $query = "SELECT s.* FROM *PREFIX*share AS s " . 
               " LEFT JOIN *PREFIX*groups_custom AS a ON a.groupname=s.share_with " .
               " LEFT JOIN *PREFIX*group_user_custom AS b ON b.gid=a.gid" .
               " WHERE b.uid=" . $db->quote($sharewith) . " AND s.share_type=" . OCP\Share::SHARE_TYPE_GROUP . 
               " AND s.item_type='resumes' AND s.token=" . $db->quote($token); 

      $db->setQuery(PUtil::replaceOCPrefix($query));
      $groupshare = $db->loadObject();
      if(!$groupshare)
         return $shares; 

      array_push($shares, $groupshare); 
      return $shares; 
   }

   public static function getCompanyIdFromOwner($share_owner) {
      // company id is always integer, short route for quick check 
      if(is_numeric($share_owner)) {
         return PFactory::getUser($share_owner); 
      } else {
         $db = PFactory::getDbo();
         $query = "SELECT owner FROM `*PREFIX*users_extended` WHERE `uid` = " . $db->quote($share_owner);
         $db->setQuery(PUtil::replaceOCPrefix($query));
         $masteruser = $db->loadResult();
         if($masteruser)
            return PFactory::getUser($masteruser);
      }

      return null; 
   }

   public static function getMaxPermissions($resume=0) {
      if (PFactory::isMasterUser()) {
         return OCP\PERMISSION_READ   |
                OCP\PERMISSION_CREATE |
                OCP\PERMISSION_UPDATE |
                OCP\PERMISSION_DELETE |
                OCP\PERMISSION_SHARE;
      } elseif (PCompanyHelper::isJobManager()) {
         /* get jobid */
         $db = PFactory::getDbo();
         $query = "SELECT job_id FROM *PREFIX*hr_jobseeker WHERE id=" . intval($resume);
         $db->setQuery(PUtil::replaceOCPrefix($query));
         $jobid = $db->loadResult() ? $db->loadResult() : 0;
         
         /* check job manager permissions on this job id */
         /* if true, return every permission bit */
         if (PCompanyHelper::checkJobManagerPermissions($jobid)) {
            return OCP\PERMISSION_READ   |
                   OCP\PERMISSION_CREATE |
                   OCP\PERMISSION_UPDATE |
                   OCP\PERMISSION_DELETE |
                   OCP\PERMISSION_SHARE;
         } else {
            return OCP\PERMISSION_READ | OCP\PERMISSION_SHARE;
         }
      } else {
         /* interviewer, get permission from sharing */
         $db = PFactory::getDbo();
         $query = "SELECT a.item_source, BIT_OR(permissions) AS permissions " .
                  " FROM *PREFIX*share AS a " .
                  " LEFT JOIN *PREFIX*groups_custom AS g ON g.groupname=a.share_with " .
                  " LEFT JOIN *PREFIX*group_user_custom AS gu ON gu.gid=g.gid" .
                  " WHERE a.item_source = " . intval($resume) .
                  " AND item_type='resumes' " .
                  " AND (a.share_with = " . $db->quote(OC_User::getUser()) .
                  "       OR (gu.uid=" . $db->quote(OC_User::getUser()) . " AND a.share_type=" . OCP\Share::SHARE_TYPE_GROUP . "))" .
                  " GROUP BY a.item_source";
         
         $db->setQuery(PUtil::replaceOCPrefix($query));
         $list = $db->loadObjectList();
         $permission = 0;
         foreach($list as $share) {
            $permission |= $share->permissions;
         }
         
         return $permission;
      }
   }

   public static function pickPermissions($permission=0) {
      // a level of permission to be forced for both server and client side 
      if($permission & OCP\PERMISSION_SHARE) {
         $permission |= OCP\PERMISSION_READ;
         $permission |= OCP\PERMISSION_UPDATE;
      }

      if($permission & OCP\PERMISSION_UPDATE) {
         $permission |= OCP\PERMISSION_READ;
      }
     
      if($permission & OCP\PERMISSION_DELETE) {
         $permission |= OCP\PERMISSION_READ;
         $permission |= OCP\PERMISSION_CREATE;
         $permission |= OCP\PERMISSION_UPDATE;
         $permission |= OCP\PERMISSION_SHARE;
      }

      return $permission; 
   }
   
   public static function getPositionEmailBySource($itemSource) {
   	$db = PFactory::getDbo();
   	$jobid = 'SELECT job_id from *PREFIX*hr_jobseeker WHERE id = '.intval($itemSource);
   	$source = 'SELECT os.item_source FROM *PREFIX*share os LEFT JOIN *PREFIX*hr_jobseeker ohj on os.item_source = ohj.id WHERE ohj.job_id IN ('.$jobid.')';
   	$query = 'SELECT DISTINCT share_with FROM *PREFIX*share WHERE item_source IN ('.$source.') AND share_with IS NOT NULL ORDER BY stime DESC LIMIT 8';
   	$db->setQuery(PUtil::replaceOCPrefix($query));
   	$list = $db->loadObjectList();
   	return $list;
   }

   public static function getShareWithList($itemSource, $shareWithArr) {
      $db = PFactory::getDbo();
      /* get pre-generated token */
      $andArr = array();
      foreach ($shareWithArr as $shareWith) {
        $andArr[] = $db->quote($shareWith);
      }
      $query = "SELECT share_with FROM *PREFIX*share " .
      " WHERE item_source=" . $db->quote($itemSource) .
      " AND item_type='resumes' " .
      " AND share_with IN (" . implode(",", $andArr). ")"; 
      $db->setQuery(PUtil::replaceOCPrefix($query));
      $sharedlist = $db->loadAssocList(null,'share_with');
      return $sharedlist;
   }
}

